// 这里需要引入vuex
import store from '@/store/index'
// 使用websocket--> this.setsocket,看main.js-->
const wsConnection = {
  wsUrl: 'http://10.19.82.148:8082/imserver/',
  socket: null, // websocoket
  // msg: {
  //   userCode: '0000',
  //   token: '200',
  //   sign: 'success',
  //   type: 'userLogin',
  //   data: {
  //     // messageCode: new Date() // 编码
  //     // userCode: '',
  //     // password: ""
  //   }
  // },

  // 这些是基础参数，与通信协议参数基本无关
  lockReturn: false, // 是否真正建立连接
  timeout: 10 * 1000, // 10秒一次心跳
  timeoutObj: null, // 心跳倒计时
  timeoutNum: null, // 断开 重连倒计时
  serverTimeoutObj: null, // 服务器心跳倒计时

  // 初始化webSocket长连接
  initWebSocket: function() {
    // const userCode = localStorage.getItem('userCode')
    // const name = localStorage.getItem('username')
    if (typeof WebSocket === 'undefined') {
    } else {
      // 实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
      // 等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
      // var socketUrl="${request.contextPath}/im/"+$("#UserCode").val();
      this.wsUrl = this.wsUrl + store.state.wsparameter.userToken
      this.wsUrl = this.wsUrl.replace('https', 'wss').replace('http', 'ws')
      if (this.socket != null) {
        this.socket.close()
        this.socket = null
        store.state.wsparameter.userToken = ''
      }
      this.socket = new WebSocket(this.wsUrl)
      this.socket.onopen = this.wsOpen
      this.socket.onclose = this.wsClose
      this.socket.onmessage = this.wsMsg
      this.socket.onerror = this.wsError
    }
  },

  // 打开websocket
  wsOpen: function() {
    // 开始websocket心跳
    wsConnection.startWsHeartbeat()
  },
  // 关闭websocket
  wsClose: function(e) {
    // store.state.wsparameter.userToken = ''
  },
  // 接收到服务端消息
  wsMsg: function(e) {
    // 打印收到服务器的内容
    const receive = JSON.parse(e.data)
    console.log(receive, '收到服务器信息receive', receive.context)
    // 服务端发送来的消息存到vuex
    store.commit('wsMsg', receive.context)
    // 每次接收到服务端消息后 重置websocket心跳
    wsConnection.resetHeartbeat()
  },
  // 报错
  wsError: function(err) {
    console.log(err, 'ws 错误')
    store.state.wsparameter.userToken = ''
    wsConnection.reconnect()
  },

  // 重新连接重启websocket
  reconnect: function() {
    const _this = this
    // if (_this.lockReturn) {
    //   return;
    // }

    // _this.lockReturn = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    _this.timeoutNum && clearTimeout(_this.timeoutNum)
    _this.timeoutNum = setTimeout(function() {
      // 新连接
      _this.initWebSocket()
      // _this.lockReturn = false;
    }, 3000)
  },
  // 开启心跳
  startWsHeartbeat: function() {
    const _this = this
    _this.timeoutObj && clearTimeout(_this.timeoutObj)
    _this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj)
    _this.timeoutObj = setInterval(function() {
      // 判断websocket当前状态
      if (_this.socket.readyState !== 1) {
        _this.reconnect()
      } else {
        const types = 'heartBeat'
        const inuserCode = {
          type: types,
          userToken: store.state.wsparameter.userToken,
          data: {
            from: store.state.wsparameter.data.from
          }
        }
        // const inmsg = { type: types, data: inuserCode }
        // 发送用户编码
        // this.socket.send(JSON.stringify(store.state.wsConnection.userCode));
        wsConnection.sendMessage(inuserCode)
      }
    }, _this.timeout)
  },

  // 重置websocket心跳
  resetHeartbeat: function() {
    const _this = this
    clearTimeout(_this.timeoutObj)
    clearTimeout(_this.serverTimeoutObj)
    _this.startWsHeartbeat()
  },

  sendMessage(index) {
    if (this.socket.readyState === 1) {
      index = JSON.stringify(index)
      this.socket.send(
        index
      )
    }
  }
}

export default wsConnection
